package cn.lanchengkeji.datafillingsystem.controller;



import cn.lanchengkeji.datafillingsystem.common.ResponseBean;
import cn.lanchengkeji.datafillingsystem.common.StatusCode;
import cn.lanchengkeji.datafillingsystem.entity.Operation;
import cn.lanchengkeji.datafillingsystem.service.IOperationService;
import cn.lanchengkeji.datafillingsystem.utils.Utils;
import cn.lanchengkeji.datafillingsystem.vo.OperationVO;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 操作权限 前端控制器
 * </p>
 *
 * @author Yixu
 * @since 2018-11-29
 */
@Api(hidden = false, tags = {"操作权限 前端控制器"})
@RestController
@RequestMapping("/operation")
public class OperationController extends BaseController {

    // 日志
    private static Logger logger = LoggerFactory.getLogger(OperationController.class);

    @Resource
    private IOperationService iOperationService;

    /**
     * 添加权限：登陆后才能操作
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(hidden = false, value = "添加权限", notes = "登陆才能操作")
    @RequiresAuthentication
    @RequiresPermissions("operation:create")
    @RequestMapping(value = "/insertOperation", method = RequestMethod.POST)
    public ResponseBean insertOperation(
            HttpServletRequest request,
            @RequestBody OperationVO operationVOParam
    ) throws Exception {

        // 获取登陆系统用户名，存入日志
        Integer userId = this.getLoginUser().getId();
        this.recordOperationLog(request, "添加权限", userId, "新增");

        // 插入
        Operation operation = new Operation();

        // 权限名称
        if (Utils.notEmpty(operationVOParam.getOperationName())) {
            operation.setOperationName(operationVOParam.getOperationName());
        }


        String codePre = "";
        String codeSuf = "";
        // 权限前缀String
        if (Utils.notEmpty(operationVOParam.getCodePre())) {
//            String code = operationVOParam.getCodePre();
//            String group= "sys_role";
//            codePre = iDictionaryService.getValueByGroupAndCode(group,code).getDictValue();
            codePre = operationVOParam.getCodePre();
        }

        // 权限后缀List<String>
        if (Utils.notEmpty(operationVOParam.getCodeSuf())) {
            List<String> suffixs = operationVOParam.getCodeSuf();
//            String group = "sys_operation";
            for (String suffixCode : suffixs) {
//                codeSuf += iDictionaryService.getValueByGroupAndCode(group,suffixCode).getDictValue()+",";
                codeSuf += suffixCode + ",";
            }
        }

        if (Utils.notEmpty(codePre) && Utils.notEmpty(codeSuf)) {
            codeSuf = codeSuf.substring(0, codeSuf.length() - 1);
            operation.setPermissionCode(codePre + ":" + codeSuf);
        }


//        if(Utils.notEmpty(operationMap.get("permissionCode"))){
//            operation.setPermissionCode((String)operationMap.get("permissionCode"));
//        }

        return iOperationService.insertOperation(operation);
    }


    /**
     * 修改权限：登陆后才能操作
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(hidden = false, value = "修改权限", notes = "登陆才能操作")
    @RequiresAuthentication
    @RequiresPermissions("operation:edit")
    @RequestMapping(value = "/updateOperation", method = RequestMethod.POST)
    public ResponseBean updateOperation(
            HttpServletRequest request,
            @RequestBody OperationVO operationVOParam
    ) throws Exception {

        // 获取登陆系统用户名，存入日志
        Integer userId = this.getLoginUser().getId();
        this.recordOperationLog(request, "修改权限", userId, "修改");

        if (Utils.notEmpty(operationVOParam.getId())) {

            // 修改菜单
            Operation operation = new Operation();
            if (Utils.notEmpty(operationVOParam.getOperationName())) {
                operation.setOperationName(operationVOParam.getOperationName());
            }

            String codePre = "";
            String codeSuf = "";
            // 权限前缀String
            if (Utils.notEmpty(operationVOParam.getCodePre())) {
//                String code = operationVOParam.getCodePre();
//                String group= "sys_role";
//                codePre = iDictionaryService.getValueByGroupAndCode(group,code).getDictValue();
                codePre = operationVOParam.getCodePre();
            }

            // 权限后缀List<String>
            if (Utils.notEmpty(operationVOParam.getCodeSuf())) {
                List<String> suffixs = operationVOParam.getCodeSuf();
//                String group = "sys_operation";
                for (String suffixCode : suffixs) {
//                    codeSuf += iDictionaryService.getValueByGroupAndCode(group,suffixCode).getDictValue()+",";
                    codeSuf += suffixCode + ",";
                }
            }

            if (Utils.notEmpty(codePre) && Utils.notEmpty(codeSuf)) {
                codeSuf = codeSuf.substring(0, codeSuf.length() - 1);
                operation.setPermissionCode(codePre + ":" + codeSuf);
            }

//            if(Utils.notEmpty(operationMap.get("permissionCode"))){
//                operation.setPermissionCode((String)operationMap.get("permissionCode"));
//            }
            operation.setId(operationVOParam.getId());
            return iOperationService.updateOperation(operation);
        } else {
            return new ResponseBean(StatusCode.NOT_FOUND, null);
        }

    }

    /**
     * 删除权限：登陆后才能操作
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(hidden = false, value = "删除权限", notes = "登陆才能操作")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "权限id", dataType = "Integer", paramType = "query", required = true),
    })
    @RequiresAuthentication
    @RequiresPermissions("operation:delete")
    @RequestMapping(value = "/deleteOperation", method = RequestMethod.POST)
    public ResponseBean deleteOperation(
            HttpServletRequest request,
            @RequestBody OperationVO operationVOParam
    ) throws Exception {

        // 获取登陆系统用户名，存入日志
        Integer userId = this.getLoginUser().getId();
        this.recordOperationLog(request, "删除权限", userId, "删除");

        if (Utils.notEmpty(operationVOParam.getId())) {

            // 删除
            Operation operation = new Operation();
            operation.setId(operationVOParam.getId());
            return iOperationService.deleteOperation(operation);
        } else {
            return new ResponseBean(StatusCode.NOT_FOUND, null);
        }

    }


    /**
     * 查看权限：登陆后才能操作
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(hidden = false, value = "查看权限", notes = "登陆才能操作")
    @RequiresAuthentication
    @RequiresPermissions("operation:view")
    @RequestMapping(value = "/selectOperation", method = RequestMethod.POST)
    public ResponseBean selectOperation(
            @RequestBody OperationVO operationVOParam,
            @RequestParam(value = "currentPage", required = false, defaultValue = "1") Integer currentPage,
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize
    ) throws Exception {

        // 获取登陆系统用户名，存入日志
        Object obj = SecurityUtils.getSubject().getPrincipal();
        logger.debug((String) obj);

        if (Utils.notEmpty(operationVOParam.getId())) {

            // 查询单条权限记录
            Operation operation = new Operation();
            operation.setId(operationVOParam.getId());
            return new ResponseBean(StatusCode.OK, iOperationService.selectOneOperation(operation));
        } else {

            // 查询全部权限（翻页查询）
            if (pageSize == 0) {
                pageSize = Integer.MAX_VALUE;
            }

            Operation searchOperation = new Operation();
            if (Utils.notEmpty(operationVOParam.getOperationName())) {
                searchOperation.setOperationName(operationVOParam.getOperationName());
            }
            if (Utils.notEmpty(operationVOParam.getPermissionCode())) {
                searchOperation.setPermissionCode(operationVOParam.getPermissionCode());
            }

            Page<Operation> page = new Page(currentPage, pageSize);
            page = iOperationService.pageOperation(page, searchOperation);
            return new ResponseBean(StatusCode.OK, page);
        }

    }
}
